package com.example.sh_crosses.login;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.TextView;

import com.example.sh_crosses.R;
import com.example.sh_crosses.base.BaseActivity;
import com.example.sh_crosses.db.UserDao;

import java.util.Timer;
import java.util.TimerTask;

public class Register extends BaseActivity {
    private final String TAG = Register.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Button btnRegister = findViewById(R.id.register);
        btnRegister.setOnClickListener(v->doCheck());

        TextView goLogin = findViewById(R.id.gologin);
        goLogin.setOnClickListener(v->{startActivity(new Intent(this,Login.class));finish();});
    }

    /**
     * 验证用户名，密码，确认密码
     */
    private void doCheck(){
        TextView tvName = findViewById(R.id.usernamer);
        String name = tvName.getText().toString();
        if(TextUtils.isEmpty(name)){
            showShortToast(getResources().getString(R.string.no_empty_username));
            return;
        }
        TextView tvPass = findViewById(R.id.userpassr);
        String pass = tvPass.getText().toString();
        if(TextUtils.isEmpty(pass)){
            showShortToast(getResources().getString(R.string.no_empty_password));
            return;
        }
        TextView tvCoPass = findViewById(R.id.userconpassr);
        String copass = tvCoPass.getText().toString();
        if(!copass.equals(pass)){
            showShortToast(getResources().getString(R.string.no_equal_password));
            return;
        }
        doRegister(name,pass);
    }

    /**
     * 用户名密码进行注册
     * @param name 用户名
     * @param pass 密码
     */
    @SuppressLint("DefaultLocale")
    private void doRegister(String name, String pass){
        int result = UserDao.getInstance().insert(name,pass);
        showLog(TAG,String.format("insert-result:%d",result));
        if(result>0){
            showShortToast(getResources().getString(R.string.register_success));
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    startActivity(new Intent(Register.this,Login.class));
                    finish();
                }
            },500);
        }else{
            showShortToast(getResources().getString(R.string.register_failure));
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_from_left);
    }
}
